package us.mmapp.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import us.mmapp.HomeScreenActivity;
import us.mmapp.R;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.provider.MediaStore;
import android.widget.ImageView;

public class ThumbnailUtil
{
	private final static int FULL_IMAGE_SIZE=600;
	public static String saveThumbnail(Context c, String fileLocation)
	{
		String[] s = fileLocation.split("/");
		String name = s[s.length - 1];
		name=name.substring(0, name.length()-4)+".jpg";
		
		int fileType=FileNameUtil.getFileType(fileLocation);
		if(fileType==FileNameUtil.AUDIO)
		{
			saveBitmapToThumb(BitmapFactory.decodeResource(c.getResources(), R.drawable.audio_icon), name);
		}
		else if(fileType==FileNameUtil.PICTURE)
		{
			saveBitmapToThumb(ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(fileLocation), 200, 200), name);
		}
		else if(fileType==FileNameUtil.VIDEO)
		{
			Bitmap b=ThumbnailUtils.extractThumbnail(ThumbnailUtils.createVideoThumbnail(fileLocation, MediaStore.Images.Thumbnails.FULL_SCREEN_KIND), 200, 200);
			saveBitmapToThumb(b, name);
		}
		return HomeScreenActivity.THUMB_LOCATION+name;
	}
	private static String saveBitmapToThumb(Bitmap b, String name)
	{
		File f=new File(HomeScreenActivity.THUMB_LOCATION+name);
		try
		{
			 FileOutputStream out = new FileOutputStream(f);
		     b.compress(Bitmap.CompressFormat.PNG, 90, out);
		}
		catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return f.getAbsolutePath();
	}
	private static Bitmap getBitmapFromURL(URL url, boolean thumbnail) throws IOException
	{
		URLConnection urlConn;
		urlConn = url.openConnection();
		if(thumbnail)
			return BitmapFactory.decodeStream(urlConn.getInputStream());
		else
		{
			Bitmap b=BitmapFactory.decodeStream(urlConn.getInputStream());
			return ThumbnailUtils.extractThumbnail(b, FULL_IMAGE_SIZE, (int)((double)b.getHeight()/b.getWidth()*FULL_IMAGE_SIZE));
		}
			
	}
	public static Bitmap getBitmap(Context c, int source, boolean thumbnail)
	{
		DBOpenHelper data=new DBOpenHelper(c, "mmAppDB", DBOpenHelper.VERSION);
		SQLiteDatabase db=data.getReadableDatabase();
		Cursor dbObjects=null;
		if(thumbnail)
			dbObjects=db.rawQuery("SELECT "+ DBOpenHelper.LOCAL_THUMB+" FROM OBJECTS WHERE "+DBOpenHelper.SID+"="+source, null);
		else
			dbObjects=db.rawQuery("SELECT "+ DBOpenHelper.STOREAGE_LOCATION+" FROM OBJECTS WHERE "+DBOpenHelper.SID+"="+source, null);
        if(dbObjects.moveToFirst())
        {
        	String thumb_url = dbObjects.getString(0);
        	if (thumb_url == null) thumb_url = "";
        	if(!thumb_url.equals(""))
        	{
        		if(thumbnail)
        		{
        			Bitmap returnB=BitmapFactory.decodeFile(dbObjects.getString(0));
        			dbObjects.close();
            		db.close();
            		return returnB;
        		}
        			
        		else
        		{
            		db.close();
        			Bitmap b=BitmapFactory.decodeFile(dbObjects.getString(0));
        			dbObjects.close();
        			return ThumbnailUtils.extractThumbnail(b, FULL_IMAGE_SIZE, (int)((double)b.getHeight()/b.getWidth()*FULL_IMAGE_SIZE));
        		}
        	}
        	else
        	{
        		dbObjects.close();
        		dbObjects=db.rawQuery("SELECT * FROM OBJECTS WHERE "+DBOpenHelper.SID+"="+source, null);
        		try
				{
					dbObjects.moveToFirst();
					Bitmap b=null;
					if(thumbnail)
					{
						b=getBitmapFromURL(new URL(dbObjects.getString(DBOpenHelper.url_thumb)), thumbnail);
						SharedPreferences settings=c.getSharedPreferences("ThumbNum", 0);
						int number=settings.getInt("CurrentNum", 0);
						String savedLocation=saveBitmapToThumb(b, number+"");
						number++;
						SharedPreferences.Editor editor=settings.edit();
						editor.putInt("CurrentNum", number);
						editor.commit();
						
						
						SQLiteDatabase db1=data.getWritableDatabase();
						ContentValues cv=new ContentValues();
						cv.put(DBOpenHelper.ID, dbObjects.getString(DBOpenHelper.id));
						cv.put(DBOpenHelper.SID, dbObjects.getInt(DBOpenHelper.sid));
						cv.put(DBOpenHelper.UID, dbObjects.getInt(DBOpenHelper.uid));
						cv.put(DBOpenHelper.TYPE, dbObjects.getInt(DBOpenHelper.type));
						cv.put(DBOpenHelper.DATE_CREATED, dbObjects.getInt(DBOpenHelper.date_created));
						cv.put(DBOpenHelper.DATE_MODIFIED, dbObjects.getInt(DBOpenHelper.date_modified));
						cv.put(DBOpenHelper.LATITUDE, dbObjects.getDouble(DBOpenHelper.latitude));
						cv.put(DBOpenHelper.LONGITUDE, dbObjects.getString(DBOpenHelper.longitude));
						cv.put(DBOpenHelper.STOREAGE_LOCATION, dbObjects.getString(DBOpenHelper.storeage_location));
						cv.put(DBOpenHelper.TITLE, dbObjects.getString(DBOpenHelper.title));
						cv.put(DBOpenHelper.PRIVACY, dbObjects.getInt(DBOpenHelper.privacy));
						cv.put(DBOpenHelper.URL, dbObjects.getString(DBOpenHelper.url));
						cv.put(DBOpenHelper.URL_THUMB, dbObjects.getString(DBOpenHelper.url_thumb));
						cv.put(DBOpenHelper.SYNCED, dbObjects.getInt(DBOpenHelper.synced));
						cv.put(DBOpenHelper.DESCRIPTION, dbObjects.getString(DBOpenHelper.description));
						cv.put(DBOpenHelper.LOCAL_THUMB, savedLocation);
						db.insertWithOnConflict("objects", null, cv, SQLiteDatabase.CONFLICT_REPLACE);
						db1.close();
					}
					else 
					{
						b=getBitmapFromURL(new URL(dbObjects.getString(DBOpenHelper.url)), thumbnail);
						dbObjects.close();
					}
					return b;
				}
				catch (MalformedURLException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				finally
				{
					dbObjects.close();
					db.close();
				}
        	}
        }
        dbObjects.close();
        db.close();
		return null;
	}
	public static void setImageView(Context c, int source, ImageView v, boolean thumbnail)
	{
		v.setImageBitmap(getBitmap(c, source, thumbnail));//System.gc();
	}
}
